package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class SingleSourcePath {
    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private int s;

    public SingleSourcePath(Graph G, int s) {
        this.G = G;
        this.s = s;
        visited = new boolean[G.V()];
        pre = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            pre[i] = -1;
        }

        bfs(s);
    }

    private void bfs(int v) {
        visited[v] = true;
        pre[v] = v;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            for (Integer w : G.adj(cur)) {
                if (!visited[w]) {
                    visited[w] = true;
                    pre[w] = cur;
                    queue.add(w);
                }
            }
        }
    }

    public boolean isConnectedTo(int t) {
        G.validateVertex(t);
        return visited[t];
    }

    public Iterable<Integer> path(int t) {
        ArrayList<Integer> path = new ArrayList<>();
        if (!isConnectedTo(t)) {
            return path;
        }
        int cur = t;
        while (cur != s) {
            path.add(cur);
            cur = pre[cur];
        }
        path.add(s);
        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args) {
        String filename = SingleSourcePath.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        SingleSourcePath singleSourcePath = new SingleSourcePath(g, 0);
        System.out.println(singleSourcePath.isConnectedTo(6));
        System.out.println("0 -> 6 : "+singleSourcePath.path(6));

        System.out.println(singleSourcePath.isConnectedTo(5));
        System.out.println("0 -> 5 : " + singleSourcePath.path(5));
    }
}
